package handler

import (
	cfg "filestore/config"
	"filestore/db"
	"filestore/meta"
	"filestore/util"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"strconv"
	"time"
)

func Upload(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		// 返回上传html页面
		data, err := ioutil.ReadFile("./static/view/index.html")
		if err != nil {
			io.WriteString(w, "internel server error")
			return
		}
		io.WriteString(w, string(data))
		// 另一种返回方式:
		// 动态文件使用http.HandleFunc设置，静态文件使用到http.FileServer设置(见main.go)
		// 所以直接redirect到http.FileServer所配置的url
		// http.Redirect(w, r, "/static/view/index.html",  http.StatusFound)
	}
	file, head, err := r.FormFile("file")

	defer file.Close()
	if err != nil {
		w.Write([]byte("获取文件失败"))
		return
	}

	fileMeta := meta.FileMeta{
		FileName: head.Filename,
		Location: cfg.LocalStorePath + head.Filename,
		UploadAt: time.Now().Format("2006-01-02 15:04:05"),
	}

	newFile, e := os.Create(fileMeta.Location)
	defer newFile.Close()
	if e != nil {
		w.Write([]byte("创建文件失败"))
		return
	}

	fileSize, e := io.Copy(newFile, file)
	if e != nil {
		w.Write([]byte("保存文件失败"))
		return
	}
	fileMeta.FileSize = fileSize

	r.ParseForm()
	username := r.Form.Get("username")
	suc := db.OnUserFileUploadFinished(username, fileMeta.FileSha1,
		fileMeta.FileName, fileMeta.FileSize)
	if suc {
		http.Redirect(w, r, "/static/view/home.html", http.StatusFound)
	} else {
		w.Write([]byte("Upload Failed."))
	}

}

func GetFileMetaList(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	limitCnt, _ := strconv.Atoi(r.Form.Get("limit"))
	username := r.Form.Get("username")
	//fileMetas, _ := meta.GetLastFileMetasDB(limitCnt)
	userFiles, err := db.QueryUserFileMetas(username, limitCnt)
	if err != nil {
		w.Write([]byte("查询失败"))
		return
	}

	data := util.NewRespMsg(200, "文件列表", userFiles).JSONBytes()
	w.Write(data)

}
